// interrogation/doctor/doctor.js
const call = require('../../utils/request.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: call.host,
    nickName: '',
    avatar: '../../images/defaultHeader.png',
    talkState: false, //是否显示弹窗
    doc:{}, //医生
    doctorArr: [], //医生列表
    doctorId: null, //当前点击咨询的医生ID
    pageIndex: 1, //当前页数
    lastPageIndex: 1, //最后一页
    quesArr: [[]], //咨询记录
    wzType: 2, // 1视频 2图文
    havaYY:false, //是否有预约
    btnText:{
      'yyz':{text:'问诊',class:''},
      'wz':{text:'问诊',class:'themebg'},
      'yy':{text:'预约',class:'yellobg'},
      'no':{text:'不可预约',class:''}
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const doc = JSON.parse(wx.getStorageSync('doctor'));
    this.setData({
      doc:doc.obj,
      havaYY:doc.havaYY
    })
    this.getQuesList();

    const user = wx.getStorageSync('user');
    let obj = {nickName:user.nickname}
    if(user.avatar && user.avatar.length>0){
      obj = Object.assign(obj,{avatar:user.avatar});
    }
    this.setData(obj)
  },

  //选择问诊类型
  chooseWzType(e){
    const index = e.currentTarget.dataset.index;
    if(this.data.wzType == index) return;
    this.pageIndex = 1;
    this.setData({
      wzType:index
    })
    this.getQuesList();
  },

  //获取咨询记录
  getQuesList() {
    let pageIndex = this.data.pageIndex;
    console.log("最大页面",this.data.lastPageIndex,"当前请求页面",pageIndex)
    if (pageIndex > this.data.lastPageIndex) return;
    wx.showLoading({
      title: '正在获取数据',
      mask:true
    })
    call.post('/api/graphic/get_list', { page: pageIndex, doctor_id:this.data.doc.id,type:this.data.wzType}).then((res) =>{
      wx.hideLoading();
      console.log("获取咨询记录列表", res);
      if (res.data.code == 0) {
        let newArr = [];
        for(let i of res.data.data.list.data){
          newArr.push({
            id:i.id, doctor_id:i.doctor_id, content:i.content, type:i.type, initiator_identity:i.initiator_identity, accessory:i.accessory, duration:Math.ceil(i.duration/60), prescription:i.prescription,
            updated_at:i.updated_at, status:i.status, name:i.name, photo:res.data.data.home_domain+i.photo, position:i.position,signature:res.data.data.home_domain+i.signature
          });
        }
        if (pageIndex == 1) {
          this.setData({
            quesArr:[newArr],
            lastPageIndex: res.data.data.list.last_page,
            host:res.data.data.domain,
          })
        } else {
          this.setData({
            [`quesArr[${pageIndex-1}]`]:newArr,
            lastPageIndex: res.data.data.list.last_page
          })
        }
        // console.log(this.data.quesArr)
      }
    });
  },

  //预约问诊按钮操作
  toWz(e){
    const status = e.currentTarget.dataset.status;
    const id =  e.currentTarget.dataset.idx;
    if(status == 'yy'){ //预约操作
      if(!this.data.havaYY){
        wx.navigateTo({
          url: `../subscribe/subscribe?id=${id}`
        });
      }
    }else if(status == 'wz'){ //问诊操作
      this.showWin();
    }
  },

  //视频问诊
  video() {
    this.hideWin();
    wx.showLoading({
      title: '正在获取数据',
      mask:true
    })
    call.post('/api/camera/get_available_order',{doctor_id:this.data.doc.id}).then(function (res) {
      wx.hideLoading();
      console.log("是否已有支付", res.data.data.not_used_order);
      if (res.data.data && (res.data.data.not_used_order || res.data.data.appointment_data)) {//已支付
        wx.showLoading({
          title: '正在获取数据',
          mask:true
        })
        let trade_no = null; 
        let duration = 0;
        let isyy = 1;
        if(res.data.data.appointment_data){ //查看是否有预约
          trade_no = res.data.data.appointment_data.trade_no;
          isyy = 2;
          let endtime = res.data.data.appointment_data.start_time.toString().replace(/-/g,"/");
              endtime = new Date(endtime);
              endtime = endtime.getTime();
              
          let nowtime = new Date();
              nowtime = nowtime.getTime();
          duration = (parseFloat(nowtime)-parseFloat(endtime))/1000;
          console.log("已浪费多少秒呢",duration)
        }else if(res.data.data.not_used_order){ //正常视频问诊
          trade_no = res.data.data.not_used_order.trade_no
          duration = res.data.data.not_used_order.duration;
        }
        wx.setStorageSync('sp_duration', duration); //已用时长
        call.post('/api/camera/gen_trtc_sign',{user_id:app.globalData.sid}).then( (res1)=> {
          wx.hideLoading();
          console.log('获取签名',res1)
          if(res1.data.code == 0){
            const d = res1.data.data;
            wx.navigateTo({url:`../video/video?sdkAppid=${d.sdkAppid}&userSign=${d.userSgin}&tradeNo=${trade_no}&isyy=${isyy}`})
          }else{
            wx.showToast({
              title: '获取视频签名失败',
              icon:'none'
            })
          }
        })
        
      }else if(res.data.msg){
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
        this.hideWin();
      } else {//未支付
        wx.navigateTo({
          url: '../buy/buy?type=1' 
        });
      }
    });
  },

  //跳转到提问
  toUrl(url) {
    this.hideWin();
    wx.navigateTo({
      url: "../chat/chat?id=".concat(this.data.doc.id) 
    });
  },

  //跳转到报告页
  toReport(e) {
    const index1 = e.currentTarget.dataset.index1;
    const index2 = e.currentTarget.dataset.index2;
    var data = this.data.quesArr[index1][index2];
    app.globalData.report = data;
    wx.navigateTo({
      url: "../report/report"
    });
  },

  //跳转到详情
  toDetail(e) {
    const type = e.currentTarget.dataset.type;
    const id = e.currentTarget.dataset.idx;
    if (type == 2) {
      wx.navigateTo({
        url: "../myQuestion/myQuestion?id=".concat(id) 
      });

    }
  },

  // 显示弹窗
  showWin(id) {
    if(app.globalData.isBind == 0){
      wx.reLaunch({
        url:'../../pages/login/index/index'
      });
      return;
    }
    this.setData({
      talkState:true
    })
    app.globalData.doctorId = this.data.doc.id;
  },
  // 关闭弹窗
  hideWin() {
    this.setData({
      talkState:false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})